import { app, BrowserWindow, ipcMain } from 'electron'

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9001`
  : `file://${__dirname}/index.html`

ipcMain.on('PRINT', (event, arg) => {
  event.sender.send('PRINT_SUCCESS', 123)
})

/**
 * 文件下载
 */
ipcMain.on('download', (event, arg) => {
  const win = BrowserWindow.fromWebContents(event.sender)
  win.webContents.downloadURL(arg)
  win.webContents.session.once('will-download', (e, item, webContents) => {
    item.once('done', (ee, state) => {
      if (state === 'completed') {
        event.sender.send('download-result', true)
      } else {
        event.sender.send('download-result', false)
      }
    })
  })
})

// 打印
ipcMain.on('goPrint', (event, arg = {}) => {
  const win = BrowserWindow.fromWebContents(event.sender)
  win.webContents.print({ printBackground: true, ...arg }, function (success) {
    win.webContents.send('goPrintMessage', success)
  })
})

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    minWidth: 1366,
    minHeight: 768,
    width: 1366,
    height: 768,
    useContentSize: true,
    backgroundColor: '#007ed3'
  })
  // mainWindow.webContents.openDevTools()
  mainWindow.loadURL(winURL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
  // update(mainWindow.webContents)
  // mainWindow.once('ready-to-show', () => {
  //   mainWindow.show()
  // })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})
